'''
jsonify是flask框架中的一个扩展包，用于处理字典和json数据转换
使用jsonify方法是需要添加一句 app.config['JSON_AS_ASCII'] = False
这样可以避免中文乱码
'''
from flask import Flask, jsonify, request
from flask_cors import CORS

# configuration
app = Flask(__name__)
app.config.from_object(__name__)
app.config['JSON_AS_ASCII'] = False

DEBUG = True

CORS(app, resources={r'/*': {'origins': '*'}})

RESOURCES = [
    {
        'sn': 'A11',
        'teacher': '关羽',
        'learnt': 'yes'
    },
    {
        'sn': 'A12',
        'teacher': '赵云',
        'learnt': 'yes'
    },
    {
        'sn': 'A13',
        'teacher': '马超',
        'learnt': 'no'
    }
]


@app.route('/resources', methods=['GET', 'POST'])
def all_res():
    response_object = {'status': 'success'}
    if request.method == 'POST':
        post_data = request.json
        sn = post_data.get('sn')
        for i in RESOURCES:
            if sn == i.get('sn'):
                response_object['status'] = 'failed'
                response_object['message'] = '待添加资源资SN编号重复！'
                break
        else:
            RESOURCES.append({
                'sn': post_data.get('sn'),
                'teacher': post_data.get('teacher'),
                'learnt': post_data.get('learnt')
            })
            response_object['message'] = '资源添加成功！'
    else:
        response_object['resources'] = RESOURCES
    return jsonify(response_object)


# @app.route('/resources1/<sn>', methods=['PUT'])
# def single_res(sn):
#     response_object = {'status': 'success'}
#     if request.method == 'PUT':
#         post_data = request.get_json()
#         if remove_res(sn):
#             response_object['message'] = '资源更新成功！'
#         else:
#             response_object['message'] = '新加资源成功！'
#         RESOURCES.append({
#             'sn': sn,
#             'teacher': post_data.get('teacher'),
#             'learnt': post_data.get('learnt')
#         })
#     return jsonify(response_object)

@app.route('/resources/<sn>', methods=['PUT', 'DELETE'])
def single_updata(sn):
    response_object = {'status': 'success'}
    post_data = request.get_json()
    if request.method == 'PUT':
        for i in RESOURCES:
            if sn == i['sn']:
                RESOURCES.remove(i)
                RESOURCES.append({
                    'sn': sn,
                    'teacher': post_data.get('teacher'),
                    'learnt': post_data.get('learnt')
                })
                response_object.update({'message': '资源更新成功'})

                break
        else:
            RESOURCES.append({
                'sn': sn,
                'teacher': post_data.get('teacher'),
                'learnt': post_data.get('learnt')
            })
            response_object.update({'message': '资源更新成功'})
    elif request.method == 'DELETE':
        for i in RESOURCES:
            if sn == i['sn']:
                RESOURCES.remove(i)
                response_object.update({'message': '资源删除成功'})
                break
        else:
            response_object.update({'message': '资源删除失败'})
            response_object['status'] = 'failed'
    return jsonify(response_object)


def remove_res(sn):
    for r in RESOURCES:
        if r['sn'] == sn:
            RESOURCES.remove(r)
            return True
    return False


@app.route('/')
def hello_world():
    return jsonify(u'Hello World!')
    # return 'Hello World!'


@app.route('/open', methods=['GET'])
def open_door():
    return jsonify(u'芝麻开门!!来自FLask')


if __name__ == '__main__':
    app.run()
